package com.snail.file.service.impl;

import com.snail.file.config.FileConfigProperties;
import com.snail.file.property.LocalFile;
import com.snail.file.utils.FileUploadUtils;
import com.snail.system.api.domain.SysFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 本地文件存储
 *
 * @author snail
 */
@Service("localSysFileService")
public class LocalSysFileServiceImpl {

    @Autowired
    private FileConfigProperties properties;

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    public String uploadFile(MultipartFile file) throws Exception {
        String name = FileUploadUtils.upload(properties.getLocal().getPath(), file);
        return properties.getLocal().getDomain() + properties.getLocal().getPrefix() + name;
    }

    /**
     * file
     * @param file 文件信息
     * @return 结果
     */
    public InputStream download(SysFile file) throws Exception {
        LocalFile local = properties.getLocal();
        String path = file.getFileUrl().replace(local.getDomain() + local.getPrefix(), local.getPath());
        return Files.newInputStream(Paths.get(path));
    }

    /**
     * 删除文件
     * @param sysFile 文件信息
     */
    public void delete(SysFile sysFile) {
        LocalFile local = properties.getLocal();
        String path = sysFile.getFileUrl().replace(local.getDomain() + local.getPrefix(), local.getPath());
        File file = new File(path);
        file.delete();
    }
}
